﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using qianjing.APP;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using thousandclear.Data;
using thousandClear.Util.Setting;

namespace thousandClear.Areas.Shop.Controllers
{
    public class BulterController : BaseController
    {
        // GET: Shop/Bulter
        /// <summary>
        /// 加载管家
        /// </summary>
        /// <param name="openid">用户ID</param>
        /// <returns></returns>
        public ActionResult Index(string code, string state, string openid)
        {
            try
            {
                AppSetting setting = new AppSetting();
                string access_token = "";
                string UserName = "";
                string HeadImage = "";
                if (string.IsNullOrEmpty(openid))
                {
                    var i = GetOpenId(code);
                    openid = i.openid;
                    access_token = i.access_token;
                    //更新该用户的微信头像和名称
                    var tt = GetUserInfo(openid, access_token);
                    HeadImage = tt.headimgurl;
                    UserName = tt.nickname;

                    using (var db = new qianjingEntities())
                    {
                        var customer = db.O_Customer.FirstOrDefault(a => a.ocOpenid.Trim() == openid);
                        if (customer != null)
                        {
                            customer.ocNicName = UserName;
                            customer.ocHeadImage = HeadImage;

                            db.SaveChanges();

                        }

                    }
                }
                ViewBag.openid = openid;
                ViewBag.AuntList = null;
                string isCanPublish = "0";
                using (var db = new qianjingEntities())
                {
                    var customer = db.O_Customer.FirstOrDefault(a => a.ocOpenid == openid);
                    if (customer == null)
                    {
                        Response.Redirect("no_aunts");
                    }
                    else
                    {
                        //找到此用户信息判断是否允许评论
                        bool iscan = customer.ocIsCanCommon == null ? false : ((bool)customer.ocIsCanCommon);
                        isCanPublish = iscan ? "1" : "0";
                        

                        if (customer.ocGrades == null)
                        {
                            ViewBag.points = 0;
                        }
                        else
                        {
                            ViewBag.points = Convert.ToInt32(customer.ocGrades == null ? 0 : customer.ocGrades);
                        }
                        ViewBag.url = "../../statics/upload/";
                        var order = db.T_Order.Where(a => a.RowStatus == 5).OrderByDescending(a=>a.CreatedDate).FirstOrDefault(a => a.toOCID == customer.OCID);
                        if (order != null && !string.IsNullOrEmpty(order.toOATID))
                        {
                            string[] auntsID = order.toOATID.Split(new char[] { ',' });
                            List<O_Aunt> auntList = new List<O_Aunt>();
                            for (int i = 0; i < auntsID.Length; i++)
                            {
                                var ss = auntsID[i];
                                var aunt = db.O_Aunt.Where(a => a.OATID.ToString() == ss).FirstOrDefault();
                                if (!string.IsNullOrEmpty(aunt.oatImg))
                                {
                                    //aunt.oatImg = setting.AppUploadFolder + aunt.oatImg;
                                }
                                else
                                {
                                    //aunt.oatImg = "~/Statics/Images/shop/bulter/user.png";
                                    aunt.oatImg = "user.png";
                                }
                                if (!string.IsNullOrEmpty(aunt.oatHealthImg))
                                {
                                    //aunt.oatHealthImg = setting.AppUploadFolder + aunt.oatHealthImg;
                                    //aunt.oatHealthImg = "../../statics/upload/" + aunt.oatHealthImg;
                                }
                                else
                                {
                                    aunt.oatHealthImg = "javascript:alert('未能找到图片')";
                                }
                                if (string.IsNullOrEmpty(aunt.IDNo))
                                {
                                    aunt.IDNo = "未登记";
                                }
                                var s = aunt.OATID.ToString();
                                var temp = (from a in db.T_OrderLog
                                                //where a.tilOAID.Contains(s)
                                            where a.tilOAID == s || a.tilOAID.StartsWith(s + ",") || a.tilOAID.EndsWith("," + s) || a.tilOAID.Contains("," + s + ",")
                                            select a).Count();//统计服务次数
                                aunt.oatDesc = temp.ToString();//借用一下描述字段
                                auntList.Add(aunt);
                            }
                            ViewBag.AuntList = JsonConvert.SerializeObject(auntList);
                            ViewBag.nickName = customer.ocNicName;
                            if (!string.IsNullOrEmpty(customer.ocHeadImage))
                            {
                                ViewBag.ocHeadImage = customer.ocHeadImage;
                            }
                            else
                            {
                                ViewBag.ocHeadImage = "../../Statics/Images/shop/bulter/user.png";
                            }
                            ViewBag.isCanPublish = isCanPublish;
                        }
                        else
                        {
                            //throw new Exception(" aunt does not exist");
                            Response.Redirect("no_aunts");
                        }
                    }
                }

                
            }
            catch (Exception ex)
            {
                Util.Util.WriteLog(DateTime.Now.ToString());
                Util.Util.WriteLog("Shop/Bulter/Index Exception:");
                Util.Util.WriteLog("Input: " + openid + "," + code);
                Util.Util.WriteLog("ErrorMsg: " + ex.Message);
            }

            return View();
        }
        [HttpGet]
        public void getComment(string openid, string num)
        {//获取评论列表
            try
            {
                if (!string.IsNullOrEmpty(num))
                {
                    num = "10";
                }
                using (var db = new qianjingEntities())
                {
                    var customer = db.O_Customer.FirstOrDefault(a => a.ocOpenid == openid);
                    var order = db.T_Order.Where(a => a.RowStatus == 5).FirstOrDefault(a => a.toOCID == customer.OCID);
                    if (!string.IsNullOrEmpty(order.toOATID))
                    {
                        string[] auntsID = order.toOATID.Split(new char[] { ',' });
                        List<T_Comment> commentList = new List<T_Comment>();

                        for (int i = 0; i < auntsID.Length; i++)
                        {
                            string _id = auntsID[i];
                            int _num = 0;
                            int.TryParse(num, out _num);
                            var record = (from a in db.T_Comment
                                              //where a.tcGrades8.Contains(_id)
                                          where (a.tcGrades8 == _id || a.tcGrades8.StartsWith(_id + ",") || a.tcGrades8.EndsWith("," + _id) || a.tcGrades8.Contains("," + _id + ","))
                                          && a.CreatedBy == openid
                                          orderby a.CreatedDate descending
                                          select a).Take(_num).ToList();
                            commentList.AddRange(record);
                        }
                        commentList = commentList.Distinct().OrderByDescending(a => a.CreatedDate).ToList();//去重排序

                        string res = JsonConvert.SerializeObject(commentList);
                        writeRes(res);
                    }
                }
            }
            catch (Exception ex)
            {
                Util.Util.WriteLog(DateTime.Now.ToString());
                Util.Util.WriteLog("Shop/Bulter/getComment Exception:");
                Util.Util.WriteLog("Input: " + openid + "," + num);
                Util.Util.WriteLog("ErrorMsg: " + ex.Message);
            }
        }
        [HttpGet]
        public void getRecord(string openid, string num)
        {//获取打赏列表
            try
            {
                if (!string.IsNullOrEmpty(num))
                {
                    num = "10";
                }
                using (var db = new qianjingEntities())
                {
                    var customer = db.O_Customer.Where(a => a.ocOpenid == openid).FirstOrDefault();
                    var cid = customer.OCID;
                    int _num = 0;
                    int.TryParse(num, out _num);
                    ViewBag.nickName = customer.ocNicName;
                    var record = (from a in db.T_Reward
                                  where a.trOCID == cid
                                  orderby a.CreatedDate descending
                                  select a).Take(_num).ToList();
                    string res = JsonConvert.SerializeObject(record);
                    writeRes(res);
                }
            }
            catch (Exception ex)
            {
                Util.Util.WriteLog(DateTime.Now.ToString());
                Util.Util.WriteLog("Shop/Bulter/getRecord Exception:");
                Util.Util.WriteLog("Input: " + openid + "," + num);
                Util.Util.WriteLog("ErrorMsg: " + ex.Message);
            }
        }
        [HttpPost]
        [ValidateInput(false)]
        public void confirmReward(string data)
        {//确认打赏
            Util.Util.WriteLog("confirmReward ininin");
            try
            {
                var form = JObject.Parse(data);
                string openid = form["openid"].Value<string>();
                int coins = form["coins"].Value<int>();
                int points = form["points"].Value<int>();
                if (coins <= 0 || points < coins)
                {
                    throw new Exception("Data Error: points not enough");
                }
                using (var db = new qianjingEntities())
                {
                    var customer = db.O_Customer.Where(a => a.ocOpenid == openid).FirstOrDefault();
                    if (customer == null)
                    {
                        Response.Redirect("no_aunts");
                    }
                    else
                    {
                        string customerName = customer.ocNicName;
                        var order = db.T_Order.Where(a => a.RowStatus == 5).FirstOrDefault(a => a.toOCID == customer.OCID);
                        if (!string.IsNullOrEmpty(order.toOATID))
                        {
                            string aunts = order.toOATID;//管家
                            string[] _aunts = aunts.Split(new char[] { ',' });

                            //插入打赏记录表
                            T_Reward rewardRecore = new T_Reward();
                            rewardRecore.trOAID = aunts;
                            rewardRecore.trOCID = (int)customer.OCID;
                            rewardRecore.trTotolRate = coins;
                            //rewardRecore.CreatedBy = customer.ocNicName;
                            rewardRecore.CreatedDate = DateTime.Now;
                            db.T_Reward.Add(rewardRecore);

                            //更新管家积分
                            double scorePerAunt = (double)coins / (double)(_aunts.Length);
                            for (int i = 0; i < _aunts.Length; i++)
                            {
                                string auntid = _aunts[i];
                                var auntRecord = db.O_Aunt.Where(a => a.OATID.ToString() == auntid).FirstOrDefault();
                                if (auntRecord.oatTotalScore != null)
                                {
                                    auntRecord.oatTotalScore += scorePerAunt;
                                }
                                else
                                {
                                    auntRecord.oatTotalScore = scorePerAunt;
                                }
                                string phone = auntRecord.oatPhone.Trim();
                                if (!string.IsNullOrWhiteSpace(phone))
                                {
                                    string msg = "工作辛苦啦！客户" + customerName + "为你打赏" + scorePerAunt + "个金币，继续努力吧！";
                                    SendSms tt = new SendSms();
                                    tt.SendMsg(phone, msg);
                                }
                            }
                            //扣减客户积分
                            customer.ocGrades -= coins;

                            db.SaveChanges();
                            writeRes("OK");
                            return;
                        }
                        else
                        {
                            throw new Exception("Data Error:no bulter exists");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Util.Util.WriteLog(DateTime.Now.ToString());
                Util.Util.WriteLog("Shop/Bulter/getRecord confirmReward:");
                Util.Util.WriteLog("Input: " + data);
                Util.Util.WriteLog("ErrorMsg: " + ex.Message);
            }
            writeRes("Error");
        }

        public ActionResult ShowImg(string imgName)
        {
            ViewBag.url = "../../statics/upload/" + imgName;
            return View();
        }
        public ActionResult no_aunts()
        {
            return View();
        }
        private void writeRes(string s)
        {
            Response.Clear();
            Response.Write(s);
            Response.End();
        }
    }
}